<template>
  <div ref="chart" style="width: 100%; height: 15vw"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import { useStore } from "@/store/index.js";

export default {
  data() {
    return {
      chart: null,
      option: {
        title: {
          text: '空气温度和湿度历史图',
          left: 'center', // 确保标题居中
          textStyle: {
            fontWeight: 'bold',
            color: '#00eaff',
            textShadow: '0px 0px 8px #00eaff' // 发光效果
          }
        },
        grid: {
          bottom: 80
        },
        toolbox: {
          feature: {
            restore: {},
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            animation: false,
            label: {
              backgroundColor: '#505765'
            }
          }
        },
        legend: {
          data: ['Flow', 'Rainfall'], // Ensure these match the series names
          top: '10%',  // 设置图例位置在顶部，避免和标题重叠
          textStyle: {
            color: '#ffffff', // 设置图例字体颜色为白色
          }
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: true,
            axisLine: {
              onZero: false,
              lineStyle: {
                color: '#ffffff' // X轴线条颜色为白色
              }
            },
            axisLabel: {
              color: '#ffffff' // X轴文字颜色为白色
            },
            data: [], // 横坐标时间点的数据将由 fetchData 填充
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#ffffff' // Y轴线条颜色为白色
              }
            },
            axisLabel: {
              color: '#ffffff' // Y轴文字颜色为白色
            }
          }
        ],
        series: [
          {
            name: 'Flow', // Ensure this name matches with the legend
            type: 'bar', // 使用柱状图
            stack: 'total', // 启用堆叠
            data: [], // 纵坐标数据由 fetchData 填充
            barWidth: '30%', // 控制柱子的宽度
            itemStyle: {
              color: '#ff4500',
              barBorderRadius: [10, 10, 0, 0] // 设置圆角
            }
          },
          {
            name: 'Rainfall', // Ensure this name matches with the legend
            type: 'bar', // 使用柱状图
            stack: 'total', // 启用堆叠
            data: [],
            barWidth: '30%', // 控制柱子的宽度
            itemStyle: {
              color: '#1e90ff',
              barBorderRadius: [10, 10, 0, 0] // 设置圆角
            }
          }
        ]
      }

    };
  },
  mounted() {
    if (this.chart) {
      this.chart.dispose();
    }

    this.chart = echarts.init(this.$refs.chart);
    this.fetchData();
  },
  beforeUnmount() {
    // 销毁echarts实例，释放资源
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    async fetchData() {
      try {
        const userStore = useStore();
        const token = userStore.token;

        const [flowData, rainfallData] = await Promise.all([
          axios.get('/api/soil/air_temp/all?sensorType=Air_temp', {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }),
          axios.get('/api/soil/air_water/all?sensorType=Air_water', {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          })
        ]);

        const flow = flowData.data;
        const rainfall = rainfallData.data;

        const startTime = new Date(flow[0].createdAt).getTime();
        const endTime = new Date(flow[flow.length - 1].createdAt).getTime();

        const timeRange = this.generateTimeRange(startTime, endTime, flow.length);

        const flowValues = flow.map(item => item.value);
        const rainfallValues = rainfall.map(item => item.value);

        this.option.xAxis[0].data = timeRange;
        this.option.series[0].data = flowValues;
        this.option.series[1].data = rainfallValues;

        this.chart.setOption(this.option);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },

    generateTimeRange(startTime, endTime, length) {
      const step = (endTime - startTime) / (length - 1);
      const timeRange = [];
      for (let i = 0; i < length; i++) {
        const time = new Date(startTime + i * step);
        timeRange.push(this.formatDate(time));
      }
      return timeRange;
    },

    formatDate(date) {
      const pad = num => (num < 10 ? '0' + num : num);
      return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
    }
  }
};
</script>

<style scoped>
/* Additional styling can be added here */
</style>
